#include "stdafx.h"
#include <MainWindow>
#include <View>
#include <Document>

MainWindow::MainWindow(QWidget *parent, Qt::WFlags flags)
	: QMainWindow(parent, flags)
{
	m_mdiArea = new QMdiArea;
	m_mdiArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
	m_mdiArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
	setCentralWidget(m_mdiArea);
	connect(m_mdiArea, SIGNAL(subWindowActivated(QMdiSubWindow*)),
		this, SLOT(windowActivated()));

	createActions();
	createMenus();

	restoreSettings();

	setWindowTitle(tr("CyberPaint"));
}

MainWindow::~MainWindow()
{

}

void MainWindow::saveSettings()
{
	QSettings settings("Cybermyth", "CyberPaintPrototype");
	settings.setValue("mainWindow/geometry", saveGeometry());
	settings.setValue("mainWindow/state", saveState());
}

void MainWindow::restoreSettings()
{
	QSettings settings("Cybermyth", "CyberPaintPrototype");

	if(!settings.value("mainWindow/geometry").toByteArray().isEmpty())
	{
		restoreGeometry(settings.value("mainWindow/geometry").toByteArray());
		restoreState(settings.value("mainWindow/state").toByteArray());
	}
	else
	{
		move(200, 200);
		resize(800, 600);
	}
}

void MainWindow::closeEvent( QCloseEvent * event )
{
	saveSettings();
}

void MainWindow::createActions()
{
	m_fileNew = new QAction("New", this);
	connect(m_fileNew, SIGNAL(triggered()), this, SLOT(onFileNew()));

	m_fileOpen = new QAction("Open", this);
	m_fileExit = new QAction("Exit", this);
}

void MainWindow::createMenus()
{
	m_fileMenu = menuBar()->addMenu(tr("&File"));
	m_fileMenu->addAction(m_fileNew);
	m_fileMenu->addAction(m_fileOpen);
	m_fileMenu->addSeparator();
	m_fileMenu->addAction(m_fileExit);
}

void MainWindow::onFileNew()
{
	View* pChild = new View;
	m_mdiArea->addSubWindow(pChild);
	pChild->show();
}

void MainWindow::onFileOpen()
{

}

void MainWindow::onFileExit()
{

}

QPointer<View> MainWindow::activeView() const
{
	if(QMdiSubWindow* pActiveSubWin = m_mdiArea->activeSubWindow())
	{
		return qobject_cast<View*>(pActiveSubWin);
	}

	return 0;
}

QPointer<Document> MainWindow::activeDocument() const
{
	QPointer<View> view = activeView();
	if(view)
	{
		return view->document();
	}

	return 0;
}

void MainWindow::windowActivated()
{

}
